package com.wealth.system.web.controller;

import iaas.annotation.Log;
import iaas.enums.StatusEnum;
import iaas.utils.RedirectMessage;
import iaas.web.JqGridRequest;
import iaas.web.JqGridResponse;
import iaas.web.JqGridUtil;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.system.entity.Role;
import com.wealth.system.entity.User;
import com.wealth.system.service.IRoleService;
import com.wealth.system.service.IUserService;
import com.wealth.system.service.ShiroUser;

/** 
* @author chan
*/
@Controller
@RequestMapping(value="/manage/system/user")
public class UserController extends BaseController{

	Logger logger = Logger.getLogger(UserController.class);
	
	@Autowired
	private IUserService userService;
	@Autowired
	private IRoleService roleService;
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		//注册自定义的属性编辑器，适合日期
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		CustomDateEditor dateEditor = new CustomDateEditor(df, true);
		// 表示如果命令对象有Date类型的属性，将使用该属性编辑器进行类型转换
		binder.registerCustomEditor(Date.class, dateEditor);
	}
	
	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Category对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 * 
	 */
	@ModelAttribute
	public void init(Model model, @RequestParam(value = "id", defaultValue = "-1") Long id) {
		try{
			if (id != -1) {
				User user = userService.get(id);
				model.addAttribute("user", user);
			}
		}catch(Exception e){
			logger.error("用户初始化错误", e);
		}
	}
	
	/**
	 * 跳转jqGrid页面
	 */
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String toList(Model model,HttpServletRequest request) {
		return "system/user/list";
	}
	
	/**
	 * 查询数据
	 */
	@RequestMapping(value="/list",method = RequestMethod.POST)
	@ResponseBody
	public JqGridResponse getJson(Model model,JqGridRequest request) {
		try{
		
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			
			Page<User> page = userService.get(corpid, request,User.class);
			return JqGridUtil.getJqGrirdResponse(page);
		}catch(Exception e){
			logger.error("用户列表错误！", e);
			return null;
		}
	}
	
	/** 
	* 查询用户信息
	*/
	@RequestMapping(value="/{id}")
	public String get(@PathVariable Long id,Model model,RedirectAttributes redirectAttributes){
		try {
			User user = userService.get(id);
			model.addAttribute("user", user);
			return "system/user/info";
		} catch (Exception e) {
			logger.error("查询用户错误,用户id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 创建用户页面
	 */
	@RequestMapping(value="/create", method = RequestMethod.GET)
	public String createForm(Model model){
		try{
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			List<Role> roleList = roleService.getRoleByCorpIdAndStatus(corpid, StatusEnum.NORMAL.getValue());
			
			model.addAttribute("user", new User());
			model.addAttribute("roleList", roleList);
			return "system/user/create";
		}catch(Exception e){
			logger.error("创建用户页面错误！", e);
			return "system/500";
		}
	}
	
	
	/** 
	* 创建用户
	*/
	@Log(method="用户创建")
	@RequestMapping(value="/create",method = RequestMethod.POST)
	public String create(@Valid User user,
			@RequestParam(value = "myRoleList",defaultValue="") List<Long> checkedRoleList,
			RedirectAttributes redirectAttributes){
		try {
			user.getRoleList().clear();
			for (Long roleid : checkedRoleList) {
				Role role = new Role(roleid);
				user.getRoleList().add(role);
			}
			
			user.setCorp(ShiroUser.getInstance().getUser().getCorp());
			user.setCreator(ShiroUser.getInstance().getUser().getUsername());
			user.setCreatetime(new Date());
			user.setStatus(StatusEnum.NORMAL.getValue());
			userService.save(user);
			
			redirectAttributes.addFlashAttribute("message",  RedirectMessage.setShowTipSuccess("创建用户成功")  );
			return "redirect:/manage/system/user/list";
		} catch (Exception e) {
			logger.error("创建用户错误", e);
			return "system/500";
		}
	}
	
	
	/** 
	* 编辑用户页面
	*/
	@RequestMapping(value="/update/{id}")
	public String updateForm(Model model,@PathVariable Long id,RedirectAttributes redirectAttributes){
		try {
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			List<Role> roleList = roleService.getRoleByCorpIdAndUserIdAndStatus(corpid, id, StatusEnum.NORMAL.getValue());
			model.addAttribute("roleList", roleList);
			
			System.out.println("***************************");
			for(Role role : roleList){
				System.out.println(role);
			}
			System.out.println("***************************");
			
			User user = userService.get(id);
			model.addAttribute("user", user);
			return "system/user/update";
		} catch (Exception e) {
			logger.error("编辑用户页面错误,用户id="+id, e);
			return "system/500";
		}
	}
	
	/** 
	* 编辑用户
	*/
	@Log(method="用户修改")
	@RequestMapping(value="/update/{id}",method = RequestMethod.POST)
	public String update(Model model,@Valid @ModelAttribute("user") User user,@PathVariable Long id,
			@RequestParam(value = "myRoleList",defaultValue="") List<Long> checkedRoleList,
			RedirectAttributes redirectAttributes){
		try {
			user.getRoleList().clear();
			for (Long roleid : checkedRoleList) {
				Role role = new Role(roleid);
				user.getRoleList().add(role);
			}
			
			userService.save(user);
			redirectAttributes.addFlashAttribute("message",  RedirectMessage.setShowTipSuccess("编辑用户成功"));
			return "redirect:/manage/system/user/list";
		} catch (Exception e) {
			logger.error("编辑用户错误,用户id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 删除用户
	 */
	@RequestMapping(value="/delete/{id}")
	public String detele(Model model,RedirectAttributes redirectAttributes,@PathVariable Long id){
		try {
			userService.deleteLogical(id);
			redirectAttributes.addFlashAttribute("message",  RedirectMessage.setShowTipSuccess("删除用户成功"));
			return "redirect:/manage/system/user/list";
		} catch (Exception e) {
			logger.error("删除用户错误,用户id="+id, e);
			return "system/500";
		}
	}
	

	/**
	 * 停用
	 */
	@RequestMapping(value="/disable/{id}",method = RequestMethod.GET)
	public String disable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			userService.updateStatus(id, StatusEnum.STOP.getValue());
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("停用成功"));
			return "redirect:/manage/system/user/list";
		}catch(Exception e){
			logger.error("停用错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 启用
	 */
	@RequestMapping(value="/enable/{id}",method = RequestMethod.GET)
	public String enable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			userService.updateStatus(id, StatusEnum.NORMAL.getValue());
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("启用成功"));
			return "redirect:/manage/system/user/list";
		}catch(Exception e){
			logger.error("启用错误,id="+id,e);
			return "system/500";
		}
	}
	
	
	/** 
	* 导出用户信息列表
	*/
	@RequestMapping(value="/export",method = RequestMethod.POST)
	public String export(Model model,RedirectAttributes redirectAttributes){
		try {
			return "redirect:/manage/system/user/list";
		} catch (Exception e) {
			logger.error("导出用户信息列表错误", e);
			return "system/500";
		}
	}

	
	/**
	 * 用户名是否唯一
	 * 2015-07-15 by chan
	 * ----------- 参数说明 ----------
	 * username 用户名
	 * 
	 * ----------- 返回说明 --------
	 * true 表示用户名唯一
	 * false 表示存在相同的用户名
	 */
	@RequestMapping(value="/unique/username",method = RequestMethod.POST)
	@ResponseBody
	public boolean unique(String username,Model model){
		try{
			return userService.unique(username);
		}catch(Exception e){
			logger.error("检查用户名是否唯一错误,username="+username, e);
			return false;
		}
	}
}
